#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

#define ITERATIONS 1000 // 调整循环次数以避免超时

int main() {
    int pipe1[2], pipe2[2];
    char byte = 'X';

    // 创建两个管道
    if (pipe(pipe1) < 0 || pipe(pipe2) < 0) {
        fprintf(2, "管道创建失败\n");
        exit(1);
    }

    int pid = fork();
    if (pid < 0) {
        fprintf(2, "fork失败\n");
        exit(1);
    } else if (pid == 0) { // 子进程
        close(pipe1[1]);    // 关闭pipe1的写端
        close(pipe2[0]);    // 关闭pipe2的读端

        for (int i = 0; i < ITERATIONS; i++) {
            if (read(pipe1[0], &byte, 1) != 1) {
                fprintf(2, "子进程读取失败\n");
                exit(1);
            }
            if (write(pipe2[1], &byte, 1) != 1) {
                fprintf(2, "子进程写入失败\n");
                exit(1);
            }
        }

        close(pipe1[0]);
        close(pipe2[1]);
        exit(1);
    } else { // 父进程
        close(pipe1[0]);    // 关闭pipe1的读端
        close(pipe2[1]);    // 关闭pipe2的写端

        uint start = uptime(); // 获取起始时间（单位：时钟滴答）

        for (int i = 0; i < ITERATIONS; i++) {
            if (write(pipe1[1], &byte, 1) != 1) {
                fprintf(2, "父进程写入失败\n");
                exit(1);
            }
            if (read(pipe2[0], &byte, 1) != 1) {
                fprintf(2, "父进程读取失败\n");
                exit(1);
            }
        }

        uint end = uptime(); // 获取结束时间
        close(pipe1[1]);
        close(pipe2[0]);
        wait(0); // 等待子进程退出

        // 计算耗时（xv6时钟滴答间隔为10ms）
        uint ticks = end - start;
        uint ms = ticks * 10;
        uint rate = (ITERATIONS * 1000) / ms; // 转换为每秒次数

        fprintf(1, "%d次交换耗时: %d毫秒\n每秒约%d次\n", ITERATIONS, ms, rate);
        exit(1);
    }
}